﻿using Abp.ObjectMapping;
using AbpProjectTemplate.Application.Filters;
using System.Linq.Dynamic.Core;
using System.Linq;

namespace AbpProjectTemplate.Extensions
{
    public static class IQueryableExtensions
    {
        /// <summary>
        /// 排序（如果指定了排序）
        /// </summary>
        public static IQueryable<T> SortBy<T>(this IQueryable<T> query, PagedRequestFilter filter)
        {
            if (filter.SortField.HasValue())
                query = query.OrderBy($"{filter.SortField} {filter.SortDirection.ToString().ToLower()}");
            return query;
        }
        /// <summary>
        /// 使用指定的filter分页
        /// </summary>
        public static IQueryable<T> PageBy<T>(this IQueryable<T> query, PagedRequestFilter filter)
        {
            return query.Skip((filter.Page - 1) * filter.Size).Take(filter.Size);
        }
        /// <summary>
        /// 使用指定的filter分页并排序（如果指定了排序）
        /// </summary>
        public static IQueryable<T> PageAndSortBy<T>(this IQueryable<T> query, PagedRequestFilter filter)
        {
            return query.SortBy(filter).PageBy(filter);
        }

        public static IQueryable<T> ProjectTo<T>(this IQueryable query, IObjectMapper objectMapper)
        {
            return objectMapper.ProjectTo<T>(query);
        }
    }
}

